Tuesday, January 12, 2010

Use Find Method of Generic List

Is there a quick way to Find an object in a List<T> without looping through the List or using Linq? Yes; use the Find Method of the object.

If you are new to .NET, or even if you have been using it for years, but you still have outdated ways of doing things, you might be waisting developement time, resources, and performance if you do not keep up to date on new features that the .NET framework brings to the table for algorithms that you use all the time.

For example, if you need to find an object in a generic List<T>, you might still be using code like the code shown below. Suppose that you have a List<Address> and the Address object has an IsPrimary field (bool). One and only one of the objects can be primary and you need to retrieve the primary address object from the List. The "user" object has an Addressess property which is a List<Address>. The tried and proven (over and over) method for doing this would be:

   Address primaryAddress;


   foreach (Address addr in user.Addresses)
   {
       if (addr.IsPrimary)
       {
         primaryAddress = addr;
         break;
       } // if
   } // foreach


Obviously, the code shown above works just fine. But, consider the following line of code that will achieve the same result.


   Address primaryAddr =
   user.Addresses.Find(delegate(Address obj)
      { return obj.IsPrimary; });


Passing a Delegate to the Find method of the generic List<Address> finds the object that has the IsPrimary field set to true with a single line of code.

Just another shortcut that hopefully will save you some time.

Need to automatically organize your code windows? You'll be amazed how easy it is to keep the code in your code windows organized. TRY IT FREE FOR 30 DAYS BY CLICKING HERE.



Automatically generate braces in C#! Try CSharpCompleter and stop wasting valuable time needlessly typing hundreds of braces {} daily. Try CSharpCompleter for 30 DAYS FREE.



You can also email me directly at les@KnowDotNet.com.

Using a LIKE Operator in a Stored Procedure

How do I code the Stored Procedure and the parameter to it to use the LIKE operator?
The answer should seem quite simple, but it is not exactly as you would do it in dynamic sql. It is almost the same with a subtile difference. In dynamic sql, you might do something like this:

   string searchText = "register";
   string sql = "select * from FAQs where QuestionColumn LIKE '%"
      + searchText + "%'";


to create the dynamic sql statement, and it will work fine. However, it does not appear that passing a parameter value like the following code works in the Stored Procedure; at least it failed to make a find for me, even though I had copied the code from VBScript in an old ASP page, where it was working.


string searchString = "'%register%'";
   sqlCommand.Parameters.Add(new SqlParameter("@SearchString",
      SqlDbType.VarChar, 50));
   sqlCommand.Parameters[0].Value = searchString;


and the code in the stored procedure was:


   SELECT Question, Answer
   FROM SP_FAQs
   WHERE Question LIKE @SearchString
      OR Answer LIKE @SearchString


So, to get it to work, I changed the parameter setting code to:


    string searchString = "register";
   sqlCommand.Parameters.Add(new SqlParameter("@SearchString",
      SqlDbType.VarChar, 50));
   sqlCommand.Parameters[0].Value = searchString;


and the Stored Procedure code to the following:


   SELECT Question, Answer
   FROM SP_FAQs
   WHERE Question LIKE '%' + @SearchString + '%'
      OR Answer LIKE '%' + @SearchString + '%'


The subtile difference is that the adding of the "%" to the beginning and end of the parameter is done inside the Stored Procedure instead of passing it in with the parameter. Even if somehow I made a simple mistatke that was causing the search to fail, it is still better to have the stored procedure do the work of enclosing the searchString in "%" than for each call have to worry about passing in anything but the actual text for which to search.


Need to automatically organize your code windows? You'll be amazed how easy it is to keep the code in your code windows organized. TRY IT FREE FOR 30 DAYS BY CLICKING HERE.


Automatically generate braces in C#! Try CSharpCompleter and stop wasting valuable time needlessly typing hundreds of braces {} daily. Try CSharpCompleter for 30 DAYS FREE.



You can also email me directly at les@KnowDotNet.com.

Thursday, September 17, 2009

Writing Plug-Ins for Loose Coupling of Application Components

How do I write a Plug-in for an application and how do I know whether a DLL implements an Interface that my application expects? Dependency Injection and Inversion of Control are hot topics in OOP development today. These terms sound complex and their implementation can indeed be complex. There are several ways of implementing Dependency Injection, but in this article I am going to describe a type of DI that is not normally covered under the definition of this term.

Check out my article at http://www.knowdotnet.com/articles/pluginsusingreflection.html.

While you are there, take a look at Visual Class Organizer, a time saving tool for automatically organizing your classes. click on the following link to download a Free 30 Day Trial.

http://www.knowdotnet.com/articles/VisualOrganizerProductHome.html

Labels: , ,

Disable or Change the Way Windows Updates Are Performed

Are you constantly having the Windows Update popup tell you that Windows has been upadated and is going to reboot? Have you forgotten and lost some of your work because of an automatic reboot? Here is how to change the way that Windows Updates work.

Check out a new article at
http://www.knowdotnet.com/articles/windowsupdates.html

While you are there, take a look at Visual Class Organizer, a time saving tool for organizing your classes. Click the link below for a 30 Day Free Trial.

http://www.knowdotnet.com/articles/VisualOrganizerProductHome.html

Labels:

Tuesday, July 10, 2007

At KnowDotNet, I have just released a hot new product called Visual Class Organizer. If you would like to automatically organize your code window by logical groups of code elements, sort your code elements within the groups, and optionally surround the groups with Regions, it can all be done visually with Visual Class Orgainzer.

I have spent well over a year in the development of this exciting new product. It came from a need of my own to have a way to do everything that I have described above in a visual way. The product allows you to organize a code window in a matter of seconds, regardless of how much code you may have in it.

In addition to the automatic options, you can manually organize your code window with drag and drop in a dialog that provides complete freedom and power to do it your way.

Try the free 30-day trial at

http://www.knowdotnet.com/articles/VisualOrganizerProductHome.html

You can also watch a short video that demos the power of the add-in by clicking the demo link on the same page.

Labels: , ,

Thursday, December 07, 2006

Les Smith .NET Blog

I just posted a rather lengthy article on extending the functionality of the CodeModel or better yet, the FileCodeModel. In spite of the functionality that it has, it still lacks functionality and this article shows some neat tricks for finding and retrieveing code that the CodeModel cannot do.

I think you will find some help here, if you are interested in the CodeModel, Regexes, and extensibility in general. Hope you like it.

The link is

http://www.knowdotnet.com/articles/extendingthecodemodel.html

Take a look.

Friday, April 28, 2006

Programmers do the dumbest things

Ever do something really stupid in your code? I bet you can't say "No" with a straight face. But, don't you get irritated when you encounter someone else's blunders. I have found some real dillys lately and thought I might run them by anyone that ever reads my blog, which at this point is not a lot of people.

It seems that a lot of self-named .NET developers totally don't understand Exception Handling! For example, explain the need for the following Try Catch block, if you can.

private void DoNothing()
{
   try
   {
      // do some code
   }
   catch(Exception ex)
   {
      throw(ex);
   }
}

Did it never occur to the writer of this code that if they had not coded the try catch, that the results of a failure in the DoNothing method will be exactly the same. The try catch as coded basically is an unhandled exception, which could have been raised without the try catch.

Here's one more that completely baffled me when I came upon it recently.

Try
   IO.File.Move(oldPath, newPath)
Catch (ex As Exception)
   IO.File.Move(oldPath, newPath)
End Try

Go Figure! What is this? "If at first you don't succeed, Try, Try again?"

Take a minute and comment with something really dumb that you have done or seen.

Infamous Last Words

Programmers are infamous for trying to pass the buck when there appears to be a problem with their program and they are facing their accuser who is pointing the finger at them. For many years I have been amused at the new answers that the “innocent” developer comes up with before finally having to admit that they blew it. A short list is compiled below.

“Sounds like a hardware problem to me…”

“I only changed one line and it wasn’t in that area of the program…”

“It runs on my machine…”

“I tested it once and it ran ok. If it runs once, it will run every time, right?”

“I only made a change to the database; it would not cause a problem in the program…”

“The program has been running for 5 months and I never had a problem, I don’t think it’s the program…”


"Why would you ask if the change had been through QA?"

This one really backfires when you tell the user, who is a customer, “It sounds like an ID10T Error.” I personally don’t recommend that one be used at all.

Should you have some that you have heard, please comment on this blog.

Wednesday, February 15, 2006

VS2005 .NET Add-Ins Nested Menus

Writing an add-in for Visual Studio .NET always brings it's challenges. With every release of .NET, if you are an ISV, as I am, there are several challenges.

First, you have to see what features of your add-ins that Microsoft has implemented in the new IDE. When they do this, and I have never seen a new version since VB4 that did not implement something that I had previously done in one of my add-ins and it is no longer needed in a new version.

Sometimes, the way Microsoft implements it, you can find a way to do more than they have done it, and with greater functionality. You are not much of a programmer, if you can look at functionality and not improve on it, or look at a medium to large block of code and not be able to improve, reorganize, or make it be more efficient, etc.

Another challenge is to look at the new IDE and see if you can find something that is useful that MS has not implemented. If you are an application developer and you write add-ins as I do, you have an advantage over Microsoft in that you are using the IDE every minute of everyday and you constantly run into tasks that are repetitive and that just say, "automate me."

Finally, there is the challenge of finding out what has changed in the automation or extensibility model of the new release that breaks your add-ins. It's not usually hard to find out what is broken, the real challenge is to find out how to fix it.

That is the case with menus in add-ins in VS2005. Microsoft created a trimmed down version of Microsoft Office CommandBars. At first you think, "this is neat." At a second look, you find there is no free lunch. The cost here is that the command bars and their associated events do not work exactly the same as the MS Office counterpart. Especially is this true with respect to event handlers for the menus. I thought I would never get them working, and said, "nothing is this hard!" And actually it isn't; all you have to do is discover what the one way that it will work is.

I finally did and have posted an article on KnowDotNet so that you hopefully won't have the agony that I experienced. The article is at http://www.knowdotnet.com/articles/nestedmenusinvs2005.html.

I hope you will find it helpful.

Tuesday, February 14, 2006

I have just uploaded NetRefactor2005 on the KnowDotNet site. It has all the features of NetRefactor for previous versions of Visual Studio .NET. It was a while in being released because of learning to deploy addins in VS2005.

Microsoft did remove some of the "COM" ness from addins in VS2005, but the Addin Wizard does not do as much for you in the new version. It actually does nothing for you in the setup and deployment area. In fact, it does not even create a Setup project for you. Deployment is completely up to the developer. I have written an article on deployment at http://knowdotnet.com/articles/addininstallation.html. It has some useful code that will help you to get your addins deployed.

I am beginning to write articles on addin development for VS2005. I would like feedback or suggestions on articles that developers would like to see on this or other .NET subjects. I can't write on everything, but my partners and I together can take a crack at a lot of subjects.

Let me hear from you.